package pro.bbs.server.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * <p>
 * 初始化数据源基础数据源
 * </p>
 *
 * @author 杨阳
 * @since 2017年10月16日
 */
@Configuration
@MapperScan(basePackages = {"pro.bbs.server.mapper.base"}, sqlSessionFactoryRef = "baseSqlSessionTemplate")
public class BaseDataSourceConfig {

    @Value("${url}")
    private String bbsUrl;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;
    @Value("${driver-class-name}")
    private String driverClassName;
    @Value("${validation-query}")
    private String validationQuery;

    /**
     * <p>
     * 基础数据库
     * </p>
     *
     * @return {@link DataSource}
     */
    @Bean(name = "baseDS")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(bbsUrl);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setValidationQuery(validationQuery);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "baseSqlSessionTemplate")
    public SqlSessionFactory baseSqlSessionTemplate(
            @Qualifier("baseDS") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/base/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "baseTransactionManager")
    public DataSourceTransactionManager baseTransactionManager(@Qualifier("baseDS") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
